<template>
  <div class="user-form">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑用户' : '新增用户' }}</span>
          <el-button @click="handleBack">返回列表</el-button>
        </div>
      </template>

      <div v-loading="loading">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="user-form"
        >
          <!-- 基本信息 -->
          <div class="section-title">基本信息</div>
          
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
          </el-form-item>
          
          <el-form-item label="手机号码" prop="telephone">
            <el-input v-model="form.telephone" placeholder="请输入手机号码" />
          </el-form-item>
          
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入电子邮箱" />
          </el-form-item>
          
          <el-form-item label="用户头像">
            <el-upload
              class="avatar-uploader"
              :action="null"
              :http-request="uploadAvatar"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.icon" :src="form.icon" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="avatar-tip">支持jpg、png格式，大小不超过2MB</div>
          </el-form-item>

          <!-- 操作按钮 -->
          <div class="operation-buttons">
            <el-button @click="handleBack">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">保存</el-button>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getUserDetail, updateUser } from '@/api/user'
import service from '@/utils/request'
import { useAdminStore } from '@/stores/modules/admin'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const adminStore = useAdminStore()

// 判断是编辑还是新增
const isEdit = computed(() => !!route.params.id)

// 表单数据
const form = ref({
  nickName: '',
  telephone: '',
  email: '',
  icon: ''
})

// 表单验证规则
const rules = {
  nickName: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传头像
const uploadAvatar = async (options) => {
  const { file } = options
  try {
    // 显示加载状态
    const loadingInstance = ElLoading.service({
      text: '头像上传中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 使用Promise包装XMLHttpRequest
    const response = await new Promise((resolve, reject) => {
      const formData = new FormData()
      formData.append('file', file)
      
      const xhr = new XMLHttpRequest()
      // 使用管理员上传接口
      xhr.open('POST', import.meta.env.VITE_API_BASE_URL + '/files/jiang/upload', true)
      
      // 使用管理员token
      if (adminStore.accessToken) {
        xhr.setRequestHeader('Authorization', `Bearer ${adminStore.accessToken}`)
      } else {
        // 如果没有管理员token，尝试从localStorage获取
        const token = localStorage.getItem('admin_token')
        if (token) {
          xhr.setRequestHeader('Authorization', `Bearer ${token}`)
        }
      }
      
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText)
            resolve(response.data)
          } catch (e) {
            resolve(xhr.responseText)
          }
        } else {
          reject(new Error(`上传失败：${xhr.status} ${xhr.statusText}`))
        }
      }
      
      xhr.onerror = function() {
        reject(new Error('网络错误，上传失败'))
      }
      
      xhr.send(formData)
    })
    
    // 关闭加载状态
    loadingInstance.close()
    
    // 处理响应
    let imageUrl = ''
    
    if (response && typeof response === 'string') {
      imageUrl = response
    } else if (response && response.data) {
      imageUrl = typeof response.data === 'string' ? response.data : response.data.url || response.data
    } else {
      imageUrl = response
    }
    
    // 检查URL是否有效
    if (!imageUrl) {
      throw new Error('上传成功但未获取到有效的图片URL')
    }
    
    // 更新头像URL
    form.value.icon = imageUrl
    
    ElMessage.success('头像上传成功')
  } catch (error) {
    // 关闭可能存在的加载状态
    try {
      ElLoading.service().close()
    } catch (e) {
      // 忽略关闭加载状态时的错误
    }
    
    console.error('头像上传失败:', error)
    ElMessage.error(error.message || '上传失败，请重试')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化手机号
const formatTelephone = (telephone) => {
  if (!telephone) return '未设置'
  return telephone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 加载用户详情
const loadUserDetail = async () => {
  if (!isEdit.value) return
  
  loading.value = true
  try {
    const res = await getUserDetail(route.params.id)
    // 填充表单数据
    form.value = {
      nickName: res.nickName || '',
      telephone: res.telephone || '',
      email: res.email || '',
      icon: res.icon || ''
    }
  } catch (error) {
    console.error('加载用户详情失败：', error)
    ElMessage.error('加载用户详情失败')
  } finally {
    loading.value = false
  }
}

// 返回列表
const handleBack = () => {
  router.back()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    if (isEdit.value) {
      // 编辑用户
      await updateUser({
        ...form.value,
        id: route.params.id
      })
      ElMessage.success('用户信息已更新')
    } else {
      // 新增用户
      await service.post('/auth/jiang/add', form.value)
      ElMessage.success('用户已添加')
    }
    
    router.push('/jiang/users')
  } catch (error) {
    if (error === 'cancel') return
    console.error('操作失败：', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadUserDetail()
})
</script>

<style lang="scss" scoped>
.user-form {
  .form-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .section-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: bold;
    color: var(--el-text-color-primary);
  }

  .avatar-uploader {
    display: flex;
    justify-content: center;
    
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
    
    .avatar {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      object-fit: cover;
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  .avatar-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
    text-align: center;
  }

  .operation-buttons {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    gap: 20px;
  }
}
</style>
